import AutoTable from '@/components/AutoTable';
import React, { useState, useEffect } from 'react';
import { ProForm, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Avatar, Button, Input, message, Modal, Popconfirm, Tag } from 'antd';
import { doFetch, getFetch } from '@/utils/doFetch';
import { ExportOutlined } from '@ant-design/icons';

function Users() {
  const [pwd, setPwd] = useState(null);
  const columns = [
    {
      title: '头像',
      dataIndex: 'headUrl',
      key: 'headUrl',
      render: (text) => {
        return <Avatar src={text} alt="" > - </Avatar>;
      },
      search: false,
      width: 66,
    },
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '账号',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
      key: 'telephone',
      width: 120,
    },
    {
      title: '积分',
      dataIndex: 'score',
      key: 'score',
      sorter: (a, b) => a.name.length - b.name.length,
      width: 120,
      search: false
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 120,
      render: (text, record) => {
        return record.sex === 1 ? "男" : record.sex === 2 ? "女" : '';
      },
      search: false,
    },
    {
      title: '岗位',
      dataIndex: 'post',
      key: 'post',
      width: 120,
      search: false,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 220,
      valueType: "select",
      options: [
        { value: "1", label: "超级管理员" },
        { value: "2", label: "管理员" },
        { value: "3", label: "普通用户" },
      ],
      render: (text, record) => {
        const tagses = record?.role?.split(",") ?? [];
        const userRoles = {
          "1": "超级管理员",
          "2": "管理员",
          "3": "普通用户",
        };
        return tagses.map((it, i) => {
          return <Tag key={it} >{userRoles[it]}</Tag>
        })

      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 240,
      render: (_, row) => {
        return [
          <Popconfirm
            key={'reset'}
            title="修改密码"
            placement="bottomRight"
            description={<Input value={pwd} onChange={(e) => {
              setPwd(e.target.value);
            }} placeholder='输入修改的密码' />}
            onConfirm={async () => {
              let res = await doFetch({
                url: '/system/resetPassword/' + row.id,
                params: {
                  password: pwd,
                },
                method: 'PUT',
              });
              if (res.code === 0) {
                message.success('重置密码成功，密码为' + pwd);
                setPwd(null);
              }
            }}
          >
            <Button type="primary" size="small">
              修改密码
            </Button>
          </Popconfirm>,
          <Button
            type="link"
            size="small"
            key={'r'}
            onClick={async () => {
              setModal((s) => ({
                ...s,
                open: true,
                title: '绑定角色',
                id: row?.id,
                initialValues: {
                  role: row?.role?.split(",")
                },
              }));
            }}
          >
            绑定角色
          </Button>,
          <Popconfirm key={'reset'} title="将该成员移除公司" onConfirm={() => {
            doFetch({ url: `/system/removeUserFromOrg/${row.orgId}/${row.id}`, params: {}, method: "PUT" }).then(() => {
              actionRef?.current?.reload();
              message.success('移除成功！');
            });
          }}>
            <Button type="text" danger size="small">
              移除
            </Button>
          </Popconfirm>,
        ];
      },
    },
  ];

  const [modal, setModal] = useState({
    open: false,
    footer: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  const actionRef = React.useRef();

  return (
    <>
      <Modal {...modal} destroyOnClose>
        <ProForm
          initialValues={modal.initialValues}
          style={{ marginTop: 30 }}
          onFinish={async (values) => {
            let res = await doFetch({
              url: '/system/assignRole/' + modal.id,
              params: {
                role: values.role.join(','),
              },
              method: "PUT"
            });
            if (res?.code === 0) {
              message.success('绑定成功!');
              actionRef.current.reload();
              setModal((s) => ({
                ...s,
                open: false,
              }));
            }
          }}
        >
          <ProFormSelect
            options={[
              { value: "1", label: "超级管理员" },
              { value: "2", label: "管理员" },
              { value: "3", label: "普通用户" },
            ]}
            mode="multiple"
            label={'选择角色'}
            name="role"
            required
            formItemProps={{
              rules: [
                {
                  required: true,
                  message: '请选择角色!',
                },
              ],
            }}
          ></ProFormSelect>
        </ProForm>
      </Modal>
      <AutoTable
        actionRef={actionRef}
        avatar={true}
        headerTitle="成员管理"
        columns={columns}
        path={"/user"}
        pagination={false}
        actions={[
          <Button key="add" type='primary' icon={<ExportOutlined />} onClick={() => {
            message.info("导出数据到excel")
          }}
          >
            导出数据
          </Button>,
        ]}
      ></AutoTable>
    </>

  );
}

export default Users;


